package com.casstime.ec.cloud.config;

import java.io.IOException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.github.pagehelper.PageHelper;

import lombok.extern.log4j.Log4j2;
@Log4j2
public abstract class MyBatisConfig {

  @Value("${mybatis.mapperLocations}")
  private String mapperLocations;

  @Value("${mybatis.configLocation}")
  private String configLocation;

  @Value("${mybatis.typeAliasesPackage}")
  private String typeAliasesPackage;

  public static final String BASE_PACKAGE_DEFAULT = "com.casstime.ec.cloud.meeting.dao.mapper";

  protected SqlSessionFactory configureSqlSessionFactory(SqlSessionFactoryBean sessionFactoryBean, DataSource dataSource) throws IOException {
    sessionFactoryBean.setDataSource(dataSource);
    sessionFactoryBean.setTypeAliasesPackage(this.typeAliasesPackage);
    //分页插件
    PageHelper pageHelper = new PageHelper();
    Properties props = new Properties();
    props.setProperty("reasonable", "true");
    props.setProperty("supportMethodsArguments", "true");
    props.setProperty("returnPageInfo", "check");
    props.setProperty("params", "count=countSql");
    pageHelper.setProperties(props);
    //添加插件
    sessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});
    //添加XML目录
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
      sessionFactoryBean.setMapperLocations(resolver.getResources(this.mapperLocations));
      sessionFactoryBean.setConfigLocation(resolver.getResource(this.configLocation));
      return sessionFactoryBean.getObject();
    } catch (Exception e) {
      log.warn("mybatisConfig 初始化失败",e);
      throw new RuntimeException(e);
    }
  }
}

@Configuration
@MapperScan(basePackages = MyBatisConfig.BASE_PACKAGE_DEFAULT,sqlSessionFactoryRef = "defaultSqlSessionFactory")
class DefaultMyBatisConfig extends MyBatisConfig {
  @Bean
  @Primary
  public SqlSessionFactory defaultSqlSessionFactory(@Qualifier("defaultDataSource") DataSource defaultDataSource) throws Exception {
    SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
    return configureSqlSessionFactory(sessionFactoryBean, defaultDataSource);
  }
}
